package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.utils.RequestContext;
import com.itheima.user.dto.UserRelationDto;
import com.itheima.user.mapper.ApUserFanMapper;
import com.itheima.user.mapper.ApUserFollowMapper;
import com.itheima.user.pojo.ApUserFan;
import com.itheima.user.pojo.ApUserFollow;
import com.itheima.user.service.ApUserFollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * APP用户关注信息表 服务实现类
 * </p>
 *
 * @author czh
 * @since 2021-08-20
 */
@Service
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {
    @Autowired
    private ApUserFollowMapper apUserFollowMapper;

    @Autowired
    private ApUserFanMapper apUserFanMapper;

    /**
     * 关注,  取关
     * @param dto
     */
    @Override
    public void follow(UserRelationDto dto) {
        //得到用户id
        Integer userId = RequestContext.getNodeValue("id");
        //判断
        if (dto.getOperation() == 1){
            //添加关注列表
            ApUserFollow apUserFollow = new ApUserFollow();
            apUserFollow.setUserId(userId);
            apUserFollow.setFollowId(dto.getAuthorId());
            apUserFollow.setFollowName(dto.getAuthorName());
            apUserFollow.setLevel(0);
            apUserFollow.setCreatedTime(LocalDateTime.now());
            apUserFollowMapper.insert(apUserFollow);

            //添加取消列表
            ApUserFan fan = new ApUserFan();
            fan.setUserId(dto.getAuthorId());
            fan.setFansId(userId);
            fan.setFansName(RequestContext.getNodeValue("name"));
            fan.setLevel(0);
            fan.setCreatedTime(LocalDateTime.now());
            fan.setIsDisplay(1);
            fan.setIsShieldLetter(0);
            fan.setIsShieldComment(0);
            apUserFanMapper.insert(fan);

        }else {
            //移除关注
            QueryWrapper<ApUserFollow> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("follow_id",dto.getAuthorId());
            queryWrapper.eq("user_id",userId);
            apUserFollowMapper.delete(queryWrapper);
            //移除粉丝
            QueryWrapper<ApUserFan> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",dto.getAuthorId());
            wrapper.eq("fans_id",  userId);
            apUserFanMapper.delete(wrapper);

        }


    }
}
